package com.jzo2o.health.handler;

import cn.hutool.core.util.ObjectUtil;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.health.config.OrderStateMachine;
import com.jzo2o.health.enums.OrderPayStatusEnum;
import com.jzo2o.health.enums.OrderStatusEnum;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.model.dto.OrderSnapshotDTO;
import com.jzo2o.health.service.IOrdersService;
import com.jzo2o.statemachine.core.StatusChangeEvent;
import com.jzo2o.statemachine.core.StatusChangeHandler;
import com.jzo2o.statemachine.model.BizSnapshot;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * TODO
 *
 * @Author whx
 * @Date 2024/12/17 20:16
 */
@Component("order_payed")
public class OrderPayedHandler implements StatusChangeHandler<OrderSnapshotDTO> {

    @Resource
    private IOrdersService ordersService;

    @Override
    public void handler(String bizId, StatusChangeEvent statusChangeEventEnum, OrderSnapshotDTO bizSnapshot) {
        // 更新订单表
        boolean result = ordersService.lambdaUpdate()
                .eq(Orders::getId, bizId)
                .set(Orders::getOrderStatus, statusChangeEventEnum.getTargetStatus())
                .set(!ObjectUtil.isNull(bizSnapshot.getTradingChannel()), Orders::getTradingChannel, bizSnapshot.getTradingChannel())
                .set(!ObjectUtil.isNull(bizSnapshot.getTradingOrderNo()), Orders::getTradingOrderNo, bizSnapshot.getTradingOrderNo())
                .set(!ObjectUtil.isNull(bizSnapshot.getPayTime()), Orders::getPayTime, bizSnapshot.getPayTime())
                .set(!ObjectUtil.isNull(bizSnapshot.getTransactionId()), Orders::getTransactionId, bizSnapshot.getTransactionId())
                .set(Orders::getPayStatus, OrderPayStatusEnum.PAY_SUCCESS.getStatus())
                .update();
        if(!result){
            throw new DBException("更新失败");
        }

    }
}
